﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using QLTB.Data;
using QLTB.Entities;
using System.Data;
using System.Data.OleDb;
using System.Globalization;
using System.IO;
using _4rumDCT.App_Code;

namespace QuanLyThietBi.DCTEDU_.QuanTri
{
    public partial class QLTaiSan : System.Web.UI.Page
    {
        private DataSet dsDummy = null; //dummy dataset use for repeater
        private DataTable tbDummy = null; //dummy table for dataset

        protected void Page_Load(object sender, EventArgs e)
        {
            ScriptManager.GetCurrent(this).RegisterPostBackControl(this.cmdUpload);
            // Intitalization
            dsDummy = new DataSet();
            tbDummy = new DataTable();
            if (!IsPostBack)
            {
                BindPhongHoc();

                // SetInitialRow(); 
                AddColumns();

                //Add dummy row to table
                tbDummy.Rows.Add("", "", "", "Add");

                BindWithRepeater();
            }
        }

        private void AddColumns()
        {
            //Add 3 dummy coloumn, this can be increase on our need basis
            tbDummy.Columns.Add("TenThietBi");
            tbDummy.Columns.Add("ViTri");
            tbDummy.Columns.Add("NgaySuDung");
            tbDummy.Columns.Add("Button");
        }

        private void BindWithRepeater()
        {
            //add this table to dataset
            dsDummy.Tables.Add(tbDummy);

            //bind this dataset to repeater
            rpDanhSachThietBi.DataSource = dsDummy;
            rpDanhSachThietBi.DataBind();
        }

        protected void rpDanhSachThietBi_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {

        }

        protected void rpDanhSachThietBi_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            int Total = rpDanhSachThietBi.Items.Count; //get total items in repeater
            if (e.CommandName == "Add")
            {
                Total = Total + 1; //increase 1 because of add

                AddColumns();

                foreach (RepeaterItem item in rpDanhSachThietBi.Items)
                {
                    //getting the values of user entered fields
                    string tenThietBi = ((TextBox) item.FindControl("txtTenThietBi")).Text;
                    string viTri = ((TextBox) item.FindControl("txtViTri")).Text;
                    string ngaySuDung = ((TextBox) item.FindControl("txtNgaySuDung")).Text;
                    Button btnAdd = ((Button) item.FindControl("btnAddAnother"));

                    //now change button text to remove, and save user entered values in table
                    tbDummy.Rows.Add(tenThietBi, viTri, ngaySuDung, "Remove");

                }

                //Add dummy row, because we need to increase
                tbDummy.Rows.Add("", "", "", "Add");

                BindWithRepeater();
            }
            else if (e.CommandName == "Remove")
            {
                Total = Total - 1;
                tbDummy.Columns.Add("TenThietBi");
                tbDummy.Columns.Add("ViTri");
                tbDummy.Columns.Add("NgaySuDung");
                tbDummy.Columns.Add("Button");

                foreach (RepeaterItem item in rpDanhSachThietBi.Items)
                {
                    Button btnAdd = ((Button) item.FindControl("btnAddAnother"));
                    if (btnAdd != e.CommandSource) //the current row on which user click will removed
                    {
                        string tenThietBi = ((TextBox) item.FindControl("txtTenThietBi")).Text;
                        string viTri = ((TextBox) item.FindControl("txtViTri")).Text;
                        string ngaySuDung = ((TextBox) item.FindControl("txtNgaySuDung")).Text;

                        if (btnAdd.Text == "Remove")
                        {
                            tbDummy.Rows.Add(tenThietBi, viTri, ngaySuDung, "Remove");
                        }
                        else
                        {
                            tbDummy.Rows.Add(tenThietBi, viTri, ngaySuDung, "Add");
                        }
                    }

                }

                BindWithRepeater();
            }

        }

        //private void SetInitialRow()
        //{
        //    DataTable dt = new DataTable();
        //    DataRow dr = null;
        //    dt.Columns.Add(new DataColumn("RowNumber", typeof(string)));
        //    dt.Columns.Add(new DataColumn("Column1", typeof(string)));
        //    dt.Columns.Add(new DataColumn("Column2", typeof(string)));
        //    dt.Columns.Add(new DataColumn("Column3", typeof(string)));
        //    dr = dt.NewRow();
        //    dr["RowNumber"] = 1;
        //    dr["Column1"] = string.Empty;
        //    dr["Column2"] = string.Empty;
        //    dr["Column3"] = string.Empty;
        //    dt.Rows.Add(dr);
        //    //dr = dt.NewRow();

        //    //Store the DataTable in ViewState
        //    ViewState["CurrentTable"] = dt;

        //    rpDanhSachThietBi.DataSource = dt;
        //    rpDanhSachThietBi.DataBind();
        //}

        //private void AddNewRowToGrid()
        //{
        //    int rowIndex = 0;

        //    if (ViewState["CurrentTable"] != null)
        //    {
        //        DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
        //        DataRow drCurrentRow = null;
        //        if (dtCurrentTable.Rows.Count > 0)
        //        {
        //            for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
        //            {
        //                //extract the TextBox values
        //                TextBox box1 = (TextBox)rpDanhSachThietBi.Items[i-1].FindControl("txtTenThietBi");
        //                //TextBox box2 = (TextBox)Gridview1.Rows[rowIndex].Cells[2].FindControl("TextBox2");
        //                //TextBox box3 = (TextBox)Gridview1.Rows[rowIndex].Cells[3].FindControl("TextBox3");

        //                drCurrentRow = dtCurrentTable.NewRow();
        //                drCurrentRow["RowNumber"] = i + 1;

        //                dtCurrentTable.Rows[i - 1]["Column1"] = box1.Text;
        //                //dtCurrentTable.Rows[i - 1]["Column2"] = box2.Text;
        //                //dtCurrentTable.Rows[i - 1]["Column3"] = box3.Text;

        //                rowIndex++;
        //            }
        //            dtCurrentTable.Rows.Add(drCurrentRow);
        //            ViewState["CurrentTable"] = dtCurrentTable;

        //            rpDanhSachThietBi.DataSource = dtCurrentTable;
        //            rpDanhSachThietBi.DataBind();
        //        }
        //    }
        //    else
        //    {
        //        Response.Write("ViewState is null");
        //    }

        //    //Set Previous Data on Postbacks
        //    SetPreviousData();
        //}

        //private void SetPreviousData()
        //{
        //    int rowIndex = 0;
        //    if (ViewState["CurrentTable"] != null)
        //    {
        //        DataTable dt = (DataTable)ViewState["CurrentTable"];
        //        if (dt.Rows.Count > 0)
        //        {
        //            for (int i = 0; i < dt.Rows.Count; i++)
        //            {
        //                TextBox box1 = (TextBox)rpDanhSachThietBi.Items[i].FindControl("txtTenThietBi");
        //                //TextBox box2 = (TextBox)Gridview1.Rows[rowIndex].Cells[2].FindControl("TextBox2");
        //                //TextBox box3 = (TextBox)Gridview1.Rows[rowIndex].Cells[3].FindControl("TextBox3");

        //                box1.Text = dt.Rows[i]["Column1"].ToString();
        //                //box2.Text = dt.Rows[i]["Column2"].ToString();
        //                //box3.Text = dt.Rows[i]["Column3"].ToString();

        //                rowIndex++;
        //            }
        //        }
        //    }
        //}

        //protected void TextChangedEvent(object sender, EventArgs e)
        //{
        //    TextBox thisTextBox = (TextBox)sender;
        //    RepeaterItem thisRepeaterRow = (RepeaterItem)thisTextBox.Parent.Parent;
        //    //int row = thisRepeaterRow.Items.Count;

        //    //if (row == rpDanhSachThietBi.Items.Count)
        //    //{
        //        AddNewRowToGrid();
        //    //}
        //}

        private void BindPhongHoc()
        {
            TList<PhongHoc> TList_PhongHoc = DataRepository.PhongHocProvider.GetAll();
            rpPhongHoc.DataSource = TList_PhongHoc;
            rpPhongHoc.DataBind();
        }

        private void BindThietBi(int PageNo)
        {
            string WhereClause = "MaPhong=" + H_PhongHocId.Value;
            int TotalRows = 0;
            DataSet dsThietBi = DataRepository.Provider.ExecuteDataSet("ThietBi_GetPaged", WhereClause, "MaThietBi DESC",
                PageNo - 1, Pager1.PageSize);
            rpThietBi.DataSource = dsThietBi.Tables[0];
            rpThietBi.DataBind();
            try
            {
                TotalRows = Convert.ToInt32(dsThietBi.Tables[1].Rows[0][0]);
            }
            catch (Exception)
            {
            }
            Pager1.ItemCount = TotalRows;
            if (TotalRows <= Pager1.PageSize)
                Pager1.Visible = false;
            else
                Pager1.Visible = true;
        }

        protected void Pager1_Command(object sender, CommandEventArgs e)
        {
            int currnetPageIndex = Convert.ToInt32(e.CommandArgument);
            Pager1.CurrentIndex = currnetPageIndex;
            BindThietBi(currnetPageIndex);
        }

        protected void rpPhongHoc_ItemCommand(object sender, RepeaterCommandEventArgs e)
        {
            if (e.CommandName == "Select")
            {
                pnDSThietBi.Visible = true;
                int id = Convert.ToInt32(e.CommandArgument);
                H_PhongHocId.Value = id.ToString();
                litPhong.Text = ": " + DataRepository.PhongHocProvider.GetByMaPhong(id).TenPhong;
                litPhong2.Text = litPhong.Text;
                litPhong3.Text = litPhong.Text;
                Pager1.CurrentIndex = 1;
                BindThietBi(Pager1.CurrentIndex);
                BindPhongHoc();
            }
        }

        protected void cmdAdd_OnClick(object sender, EventArgs e)
        {
            pnThemThietBi.Visible = true;
            pmImportThietBi.Visible = false;
            BindThietBi(Pager1.CurrentIndex);
        }

        protected void cmdImport_OnClick(object sender, EventArgs e)
        {
            pmImportThietBi.Visible = true;
            pnThemThietBi.Visible = false;
            BindThietBi(Pager1.CurrentIndex);
        }

        public string getTenCanBo(object ob)
        {
            string id = ob.ToString();
            return DataRepository.CanBoProvider.GetByMaCanBo(id).HoTen;

        }

        protected void btnUpload_Click(object sender, EventArgs e)
        {
            Page.Form.Attributes.Add("enctype", "multipart/form-data");
             //Coneection String by default empty  
            string ConStr = "";
            //Extantion of the file upload control saving into ext because   
            //there are two types of extation .xls and .xlsx of Excel   
            //string ext = Path.GetExtension(FileUpload1.FileName).ToLower();
            string ext = ".xls";
            //getting the path of the file   
            //string path = Server.MapPath("~/Upload/TepTin/" + FileUpload1.FileName);
            string path = Server.MapPath("~/Upload/TepTin/QLTB.xls");
            //saving the file inside the MyFolder of the server  
            //FileUpload1.SaveAs(path);
            lblFileDinhKem.Text = FileUpload1.FileName + "\'s Data showing into the GridView";
            //checking that extantion is .xls or .xlsx  
            if (ext.Trim() == ".xls")
            {
                //connection string for that file which extantion is .xls  
                ConStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";
            }
            else if (ext.Trim() == ".xlsx")
            {
                //connection string for that file which extantion is .xlsx  
                ConStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
            }
            //making query  
            string query = "SELECT * FROM [Sheet1$]";
            //Providing connection  
            OleDbConnection conn = new OleDbConnection(ConStr);
            //checking that connection state is closed or not if closed the   
            //open the connection  
            if (conn.State == ConnectionState.Closed)
            {
                conn.Open();
            }
            //create command object  
            OleDbCommand cmd = new OleDbCommand(query, conn);
            // create a data adapter and get the data into dataadapter  
            OleDbDataAdapter da = new OleDbDataAdapter(cmd);
            DataSet ds = new DataSet();
            //fill the Excel data to data set  
            da.Fill(ds);
            //set data source of the grid view  
            gvExcelFile.DataSource = ds.Tables[0];
            //binding the gridview  
            gvExcelFile.DataBind();
            //close the connection  
            conn.Close();
            int GVCount = gvExcelFile.Rows.Count;
            bool updateStatus = false;
            foreach (GridViewRow GVRow in gvExcelFile.Rows)
            {
                ThietBi ent_ThietBi = new ThietBi();
                ent_ThietBi.TenThietBi = Server.HtmlDecode(GVRow.Cells[1].Text).Trim();
                ent_ThietBi.ViTri = Convert.ToInt32(Server.HtmlDecode(GVRow.Cells[2].Text).Trim());
                ent_ThietBi.NgaySuDung = Convert.ToDateTime(Common.StandardString(Server.HtmlDecode(GVRow.Cells[3].Text).Trim()));
                ent_ThietBi.MaPhong = Convert.ToInt32(Server.HtmlDecode(GVRow.Cells[0].Text).Trim());
                ent_ThietBi.TrangThai = true;
                int totalRow = 0;
                TList<ThietBi> TList_TB = DataRepository.ThietBiProvider.GetPaged("(TenThietBi like '%" + ent_ThietBi.TenThietBi + "%' and MaPhong = " + Server.HtmlDecode(GVRow.Cells[0].Text).Trim() + ")", "", 0, 0, out totalRow);
                if (TList_TB.Count == 0)
                {
                    updateStatus = DataRepository.ThietBiProvider.Insert(ent_ThietBi);
                }
                else
                {
                    ent_ThietBi.EntityState = EntityState.Changed;
                    ent_ThietBi.MaThietBi = TList_TB[0].MaThietBi;
                    updateStatus = DataRepository.ThietBiProvider.Update(ent_ThietBi);
                }
                if (!updateStatus)
                {
                    ScriptManager.RegisterStartupScript(upPanel1, this.GetType(), Constant.THATBAI, Constant.CAPNHAT_THATBAI, true);
                }
                else
                {
                    ScriptManager.RegisterStartupScript(upPanel1, this.GetType(), Constant.THANHCONG, Constant.CAPNHAT_THANHCONG, true);
                }
                BindThietBi(Pager1.CurrentIndex);
            }
        }
 

    protected void cmdSave_OnClick(object sender, EventArgs e)
        {
            bool status = false;
            foreach (RepeaterItem item in rpDanhSachThietBi.Items)
            {

                //getting the values of user entered fields
                string tenThietBi = ((TextBox)item.FindControl("txtTenThietBi")).Text;
                string viTri = ((TextBox)item.FindControl("txtViTri")).Text;
                string ngaySuDung = ((TextBox)item.FindControl("txtNgaySuDung")).Text;
                if (tenThietBi != "")
                {
                    ThietBi ent_ThietBi = new ThietBi();
                    ent_ThietBi.TenThietBi = tenThietBi;
                    ent_ThietBi.MaPhong = Convert.ToInt32(H_PhongHocId.Value);
                    ent_ThietBi.ViTri = Convert.ToInt32(viTri);
                    if (ngaySuDung.Trim() != "")
                    {
                        ent_ThietBi.NgaySuDung = DateTime.ParseExact(Common.StandardString(ngaySuDung), "dd/MM/yyyy",
                            CultureInfo.InvariantCulture);
                    }
                    ent_ThietBi.TrangThai = true;
                    status = DataRepository.ThietBiProvider.Insert(ent_ThietBi);
                }

            }
            if (!status)
            {
                ScriptManager.RegisterStartupScript(upPanel1, this.GetType(), Constant.THATBAI, Constant.CAPNHAT_THATBAI, true);
            }
            else
            {
                ScriptManager.RegisterStartupScript(upPanel1, this.GetType(), Constant.THANHCONG, Constant.CAPNHAT_THANHCONG, true);
                rpDanhSachThietBi.DataSource = null;
                rpDanhSachThietBi.DataBind();
               
                Page_Load(sender, e);
                // SetInitialRow(); 
                AddColumns();

                //Add dummy row to table
                tbDummy.Rows.Add("", "", "", "Add");
                BindWithRepeater();
                BindThietBi(Pager1.CurrentIndex);
                BindPhongHoc();
            }
        }

        protected void rpThietBi_OnItemCommand(object source, RepeaterCommandEventArgs e)
        {
            if (e.CommandName == "Delete")
            {
                int id = Convert.ToInt32(e.CommandArgument);
                DataRepository.ThietBiProvider.GetByMaThietBi(id);
                BindThietBi(Pager1.CurrentIndex);
                BindPhongHoc();
            }
        }
    }
}